import cv2 as cv
import numpy as np

img = cv.imread('IMG1.jpeg', cv.IMREAD_COLOR)
img = cv.resize(img, (600, 800))

# grabcut
mask = np.zeros(img.shape[:2],np.uint8)
width, height = img.shape[:2]
bgdModel = np.zeros((1,65),np.float64)
fgdModel = np.zeros((1,65),np.float64)

# rect = (10,10,width-30,height-30)
rect = (5, 5, img.shape[:2][1]-5, img.shape[:2][0]-5)
cv.grabCut(img,mask,rect,bgdModel,fgdModel,5,cv.GC_INIT_WITH_RECT)

mask2 = np.where((mask==2)|(mask==0),0,1).astype('uint8')
image = img*mask2[:,:,np.newaxis]

#Get the background
background = img - image

#Change all pixels in the background that are not black to white
background[np.where((background > [0,0,0]).all(axis = 2))] =[255,255,255]

#Add the background and the image
final = background + image

img2 = final.copy()
gray = cv.cvtColor(final, cv.COLOR_BGR2GRAY)
edges = cv.Canny(gray, 50, 200)
minLineLength = 50
maxLineGap = 10

lines = cv.HoughLinesP(edges, 1, np.pi/180, 40, np.array([]), minLineLength, maxLineGap)
a, b, c = lines.shape
for i in range(a):
    cv.line(img, (lines[i][0][0], lines[i][0][1]),
            (lines[i][0][2], lines[i][0][3]), (0, 0, 255), 3, cv.LINE_AA )

cv.imshow('source_foreground', img2)
cv.imshow('lines', img)
cv.waitKey(0)
cv.destroyAllWindows()
